package org.example.service;

import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelExporter {
    public void exportToExcel(String excelPath) {
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Dependencies");

        // 添加表头
        Row headerRow = sheet.createRow(0);
        headerRow.createCell(0).setCellValue("APK Name");
        headerRow.createCell(1).setCellValue("Package Name");
        headerRow.createCell(2).setCellValue("Version");

        // 从数据库读取数据
        try (Connection conn = DriverManager.getConnection("jdbc:sqlite:apk_dependencies.db");
             Statement stmt = conn.createStatement();
             ResultSet rs = stmt.executeQuery("SELECT * FROM dependencies")) {
            int rowNum = 1;
            while (rs.next()) {
                Row row = sheet.createRow(rowNum++);
                row.createCell(0).setCellValue(rs.getString("apk_name"));
                row.createCell(1).setCellValue(rs.getString("package_name"));
                row.createCell(2).setCellValue(rs.getString("version"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 保存文件
        try (FileOutputStream fos = new FileOutputStream(excelPath)) {
            workbook.write(fos);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}